package com.even.camerarecoder

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.storage.StorageManager
import android.os.storage.StorageVolume
import android.util.Log
import java.io.File

@TargetApi(Build.VERSION_CODES.N)
fun StorageVolume.getMountPath(): String = StorageVolume::class.java.getMethod("getPath").invoke(this) as String

/**
 * SdCard工具类，可以获取SD卡的路径
 */
class SDCardUtil {
    companion object {
        const val TAG = "SDCardUtil"
        /**
         * 获取SdCard的路径，如果没有，则返回null
         */
        @TargetApi(Build.VERSION_CODES.N)
        fun getSdCardPath(): String? {
            val storageManager = App.sContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager
            // 主存储器(内置存储，不可移除)：isEmmulated = true, isRemovable = false, Uuid = null
            // SDCard （外置存储，可移除）：isEmmulated = false, isRemovable = true, Uuid = 6332-3530
            storageManager.storageVolumes.forEach {storageVolume: StorageVolume ->
//                Log.i(TAG, "isEmmulated = " + storageVolume.isEmulated + ", isRemovable = " + storageVolume.isRemovable + ", Uuid = " + storageVolume.uuid + ", mounted = " + (storageVolume.state == Environment.MEDIA_MOUNTED))
                if (storageVolume.isRemovable && storageVolume.state == Environment.MEDIA_MOUNTED) {
                    val mountPath = storageVolume.getMountPath()
//                    Log.i(TAG, "SDCard.path = $mountPath")
                    return mountPath
                }
            }
            Log.e(TAG, "没有SDCard")
            return null
        }

        /** 返回SDCard的总大小，单位为字节 */
        fun getSdCardTotalSpace(sdcardPath: String?): Long {
            if (sdcardPath.isNullOrBlank()) return 0L
            val sdcardDir = File(sdcardPath)
            val totalSpace = sdcardDir.totalSpace
//            Log.d(TAG, "SDCard总大小：${Formatter.formatFileSize(NgnApplication.getContext(), totalSpace)}")
            return totalSpace
        }

        /** 返回SDCard的可用大小，单位为字节 */
        fun getSdCardUsableSpace(sdcardPath: String?): Long {
            if (sdcardPath.isNullOrBlank()) return 0L
            val sdcardDir = File(sdcardPath)
            val usableSpace = sdcardDir.usableSpace
//            Log.d(TAG, "SDCard可用大小：${Formatter.formatFileSize(NgnApplication.getContext(), usableSpace)}")
            return usableSpace
        }
    }
}